import 'package:flutter/material.dart';

class Demo extends StatelessWidget {
  bool withTree = false; // 复选框选中状态
  Widget getAlertDialog(BuildContext context) {
    return AlertDialog(
      title: Text("提示"),
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("您确定要删除当前文件吗?"),
          Row(
            children: [
              Text("同时删除子目录？ "),
              StatefulBuilder(
                builder: (context, changeState) {
                  return Checkbox(
                    value: withTree, //默认不选中
                    onChanged: (bool? value) {
                      //_setState方法实际就是该StatefulWidget的setState方法，
                      //调用后builder方法会重新被调用
                      changeState(() {
                        //更新选中状态
                        withTree = value!;
                      });
                    },
                  );
                },
              ),
            ],
          ),
        ],
      ),
      actions: <Widget>[
        TextButton(
          child: Text("取消"),
          onPressed: () => Navigator.of(context).pop(), // 关闭对话框
        ),
        TextButton(
          child: Text("删除"),
          onPressed: () {
            //关闭对话框并返回true
            Navigator.of(context).pop(withTree);
          },
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("对话框上所有可能会改变状态的组件都得单独封装在一个在内部管理状态的StatefulWidget中，这样不仅麻烦，而且复用性不大"),
        Text("引入封装state的神奇方式：StatefulBuilder, 虽然不是很理解，但是确实很厉害，这大概就是所谓的不明觉厉了吧"),
        //点击该按钮后弹出对话框
        ElevatedButton(
          child: Text("AlertDialog"),
          onPressed: () async {
            //弹出对话框并等待其关闭
            bool? delete = await showDialog<bool>(
              context: context,
              builder: getAlertDialog,
            );
            if (delete == null) {
              print("取消删除");
            } else {
              print("已确认删除。 删除子文件: $delete");
              //... 删除文件
            }
          },
        ),
      ],
    );
  }
}

class StatefulBuilder extends StatefulWidget {
  const StatefulBuilder({
    Key? key,
    required this.builder,
  });

  final StatefulWidgetBuilder builder;

  @override
  State createState() => _StatefulBuilderState();
}

class _StatefulBuilderState extends State<StatefulBuilder> {
  @override
  Widget build(BuildContext context) => widget.builder(context, setState);
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(body: Demo()),
  ));
}
